﻿'Programmer: Scuba156
'Program Name: CONSaver

Imports System.IO
Imports X360
Imports Microsoft.VisualBasic.FileIO


Public Class Main
    Dim myBrush As Brush = Brushes.Black
    Private counter1 As Integer
    Friend Backup As Boolean = True
    Friend STFSFilePath As String
    Dim sortColumn As Integer = -1
    Friend counter, ResignCount, ErrorCount, GamesCount As Integer
    Friend DeviceID, ConsoleID, ProfileID As String
    'Friend ProfileIDRAW As String
    'Friend ConsoleIDRAW As String
    'Friend DeviceIDRAW As String
    Friend ChilkatKey As String
    Friend EditProfile As Boolean

    Public Sub New()
        InitializeComponent()
        X360.XAbout.WriteLegalLocally()
    End Sub

    Private Sub OpenButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenButton.Click, AddToolStripMenuItem.Click, AddToolStripMenuItem1.Click, SavesListView.DragDrop
        If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            SavesListView.Sorting = SortOrder.None
            GetFiles.FolderPath = FolderBrowserDialog1.SelectedPath
            GetSaves()
            If SavesListView.Items.Count <> -1 Then
                BackupsCheckBox.Enabled = True
                UnflagButton.Enabled = True
                ResignCheckBox.Enabled = True
                RestoreBackupsToolStripMenuItem.Enabled = True
            End If

        End If
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        LogListBox.Items.Add("Xbox1Crew/XeLove Presents CONSaver")
        LogListBox.Items.Add("CONSaver Started...")
        LogListBox.Items.Add("   Click Add to select a folder to start...")
        LogListBox.SelectedIndex = LogListBox.Items.Count - 1
        LogListBox.SelectedIndex = -1

        AddHandler SavesListView.ColumnClick, AddressOf SavesListView_ColumnClick
        If File.Exists(Application.StartupPath & "\Config.ini") Then
            Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("Config.ini")
                MyReader.TextFieldType = FileIO.FieldType.Delimited
                MyReader.SetDelimiters("=")
                Dim currentRow As String()
                While Not MyReader.EndOfData
                    Try
                        currentRow = MyReader.ReadFields()
                        If currentRow(0) = "DeviceID" Then
                            DeviceID = currentRow(1)
                        ElseIf currentRow(0) = "ProfileID" Then
                            ProfileID = currentRow(1)
                        ElseIf currentRow(0) = "ConsoleID" Then
                            ConsoleID = currentRow(1)
                            If ConsoleID.Length = 7 Then
                                ConsoleID = "0" & ConsoleID
                            End If
                        ElseIf currentRow(0) = "Edit Profile" Then
                            EditProfile = currentRow(1)
                        ElseIf currentRow(0) = "Host" Then
                            HostName = currentRow(1)
                        ElseIf currentRow(0) = "Username" Then
                            UserName = currentRow(1)
                        ElseIf currentRow(0) = "Password" Then
                            Password = currentRow(1)
                        ElseIf currentRow(0) = "Passive" Then
                            Passive = currentRow(1)
                        End If
                    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                        MessageBox.Show("Line " & ex.Message & "is not valid and will be skipped.")
                    End Try
                End While
            End Using
        End If
        If File.Exists(Application.StartupPath & "\ChilkatLicence.lnc") Then
            Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("ChilkatLicence.lnc")
                MyReader.TextFieldType = FileIO.FieldType.Delimited
                MyReader.SetDelimiters("=")
                Dim currentRow As String()
                While Not MyReader.EndOfData
                    Try
                        currentRow = MyReader.ReadFields()
                        If currentRow(0) = "Licence" Then
                            ChilkatKey = currentRow(1)
                        Else
                            ChilkatKey = "30-Day Trial"
                        End If

                    Catch ex As Exception
                        MessageBox.Show("Error reading Chilkat FTP Licence", "error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        ChilkatKey = "30-Day Trial"
                    End Try

                End While
            End Using
        Else
            ChilkatKey = "30-Day Trial"
        End If

        If Directory.Exists(Application.StartupPath & "\FTP\") Then
            If Directory.GetDirectories(Application.StartupPath & "\FTP\").Count > 0 Then
                CleanDir()
            End If
        End If
        'Dim hmm As Net.WebRequestMethods.Ftp '= New Net.WebRequestMethods.Ftp

        'Net.WebRequestMethods.Ftp.DownloadFile.

        success = ftp.UnlockComponent(ChilkatKey)
        If (success <> True) Then
            'MessageBox.Show(Net.WebRequestMethods.Ftp.DownloadFile.)
        Else
        End If


    End Sub

    Private Sub UnflagButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UnflagButton.Click
        SavesListView.Sorting = SortOrder.None
        Dim BackupCount, FlagCount, SkipCount As Integer

        ResignCount = 0
        counter = 0
        ErrorCount = 0
        If Backup = False Then
            If MessageBox.Show("Are you aure you want to overwrite without creating a backup first?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.No Then
                Exit Sub
            End If

        End If
        ToolStripProgressBar1.Value = 0
        ToolStripProgressBar1.Maximum = GamesCount


        Do Until counter = SavesListView.Items.Count
            Try
                If SavesListView.Items(counter).SubItems(1).Text <> "FFFFFFFFFFFFFFFF" Or SavesListView.Items(counter).SubItems(4).Text <> ProfileID Or SavesListView.Items(counter).SubItems(5).Text <> DeviceID Or SavesListView.Items(counter).SubItems(6).Text <> ConsoleID Then
                    If SavesListView.Items(counter).SubItems(0).Text <> "Forza Motorsport 2" And SavesListView.Items(counter).SubItems(3).Text.Contains("tuning".ToUpper) = False Then


                        If Backup = True Then
                            Dim backuppath As String
                            Dim testflag As String
                            Dim sr As BinaryReader = New BinaryReader(File.Open(SavesListView.Items(counter).SubItems(2).Text, FileMode.Open))
                            sr.BaseStream.Seek(556, SeekOrigin.Begin)
                            FlagFind = System.Net.IPAddress.HostToNetworkOrder(sr.ReadInt64())

                            testflag = Hex(FlagFind)
                            sr.Close()

                            If testflag <> "FFFFFFFFFFFFFFFF" Or SavesListView.Items(counter).SubItems(4).Text <> ProfileID Or SavesListView.Items(counter).SubItems(5).Text <> DeviceID Or SavesListView.Items(counter).SubItems(6).Text <> ConsoleID Then
                                If SavesListView.Items(counter).SubItems(2).Text.Contains(Application.StartupPath & "\FTP\") Then
                                    backuppath = Application.StartupPath & "\Backups\" & SavesListView.Items(counter).SubItems(2).Text.Replace(Application.StartupPath & "\FTP", "")
                                Else
                                    backuppath = Application.StartupPath & "\Backups\" & SavesListView.Items(counter).SubItems(2).Text.Replace(GetFiles.FolderPath & "\", "")
                                End If

                                ' MsgBox(backuppath)
                                If Directory.Exists(backuppath) = False Then
                                    My.Computer.FileSystem.CopyFile(SavesListView.Items(counter).SubItems(2).Text, backuppath, True)
                                End If
                                LogListBox.Items.Add("   Created backup in " & backuppath)
                                LogListBox.SelectedIndex = LogListBox.Items.Count - 1
                                LogListBox.SelectedIndex = -1
                                BackupCount += 1
                            End If
                        End If
                        Dim fs As New FileStream(SavesListView.Items(counter).SubItems(2).Text, FileMode.Open, FileAccess.ReadWrite)
                        fs.Seek((556), SeekOrigin.Begin)
                        Dim i As Integer = 0
                        Do While i <> 8

                            fs.WriteByte(&HFF)

                            i += 1
                        Loop
                        fs.Close()

                        LogListBox.Items.Add("   Removed flag in " & SavesListView.Items(counter).Text)
                        LogListBox.SelectedIndex = LogListBox.Items.Count - 1
                        LogListBox.SelectedIndex = -1
                        FlagCount += 1


                        STFSFilePath = SavesListView.Items(counter).SubItems(2).Text

                        If EditProfile = False Then
                            If SavesListView.Items(counter).SubItems(7).Text = "Saved Game" Then
                                BinaryReadWrite.WriteProfileID()
                                BinaryReadWrite.WriteConsoleID()
                                BinaryReadWrite.WriteDeviceID()
                            End If
                        Else
                            If SavesListView.Items(counter).SubItems(7).Text <> "Profile" Then
                                BinaryReadWrite.WriteProfileID()
                            End If
                            BinaryReadWrite.WriteConsoleID()
                            BinaryReadWrite.WriteDeviceID()
                        End If

                        If ResignCheckBox.Checked = True Then
                            resigner.OpenResign(SavesListView.Items(counter).SubItems(2).Text, e)

                        End If

                    Else
                        LogListBox.Items.Add("   Skipped " & SavesListView.Items(counter).Text)
                        LogListBox.SelectedIndex = LogListBox.Items.Count - 1
                        LogListBox.SelectedIndex = -1
                        SkipCount += 1
                    End If

                Else
                    LogListBox.Items.Add("   Skipped " & SavesListView.Items(counter).Text)
                    LogListBox.SelectedIndex = LogListBox.Items.Count - 1
                    LogListBox.SelectedIndex = -1
                    SkipCount += 1
                End If
                ToolStripProgressBar1.Value += 1
            Catch ex As Exception

                counter1 = counter

                LogListBox.Items.Add("   Error removing flag in " & SavesListView.Items(counter).Text & ":: " & Environment.NewLine & ex.Message)

                LogListBox.SelectedIndex = LogListBox.Items.Count - 1
                LogListBox.SelectedIndex = -1
                ErrorCount += 1
            End Try

            counter += 1
        Loop
        'GetSaves()
        If FlagCount = 1 Then
            LogListBox.Items.Add("   " & BackupCount & " backup created")
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
            LogListBox.SelectedIndex = -1
        Else
            LogListBox.Items.Add("   " & BackupCount & " backups created")
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
            LogListBox.SelectedIndex = -1
        End If

        If FlagCount = 1 Then
            LogListBox.Items.Add("   " & FlagCount & " flag edited")
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
            LogListBox.SelectedIndex = -1
        Else
            LogListBox.Items.Add("   " & FlagCount & " flags edited")
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
            LogListBox.SelectedIndex = -1
        End If

        If ResignCount = 1 Then
            LogListBox.Items.Add("   " & ResignCount & " file resigned")
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
            LogListBox.SelectedIndex = -1
        Else
            LogListBox.Items.Add("   " & ResignCount & " files resigned")
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
            LogListBox.SelectedIndex = -1
        End If

        If SkipCount = 1 Then
            LogListBox.Items.Add("   " & SkipCount & " skipped file")
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
            LogListBox.SelectedIndex = -1
        Else
            LogListBox.Items.Add("   " & SkipCount & " skipped files")
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
            LogListBox.SelectedIndex = -1
        End If

        If ErrorCount = 1 Then
            LogListBox.Items.Add("   " & ErrorCount & " Error")
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
            LogListBox.SelectedIndex = -1
        Else
            LogListBox.Items.Add("   " & ErrorCount & " Errors")
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
            LogListBox.SelectedIndex = -1
        End If

        LogListBox.Items.Add("done.")
        LogListBox.SelectedIndex = LogListBox.Items.Count - 1
        LogListBox.SelectedIndex = -1
        RefreshList()
    End Sub

    Private Sub BackupsCheckBox_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BackupsCheckBox.CheckedChanged
        Backup = BackupsCheckBox.Checked
    End Sub

    Friend Sub SavesListView_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs)
        ' Determine whether the column is the same as the last column clicked.
        If e.Column <> sortColumn Then
            ' Set the sort column to the new column.
            sortColumn = e.Column
            ' Set the sort order to ascending by default.
            SavesListView.Sorting = SortOrder.Ascending
        Else
            ' Determine what the last sort order was and change it.
            If SavesListView.Sorting = SortOrder.Ascending Then
                SavesListView.Sorting = SortOrder.Descending
            Else
                SavesListView.Sorting = SortOrder.Ascending
            End If
        End If
        ' Call the sort method to manually sort.
        SavesListView.Sort()
        ' Set the ListViewItemSorter property to a new ListViewItemComparer
        ' object.
        SavesListView.ListViewItemSorter = New ListViewItemComparer(e.Column, SavesListView.Sorting)
    End Sub

    Private Sub RemoveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RemoveButton.Click, RemoveToolStripMenuItem.Click
        For Each Save As ListViewItem In SavesListView.SelectedItems
            Save.Remove()
            GamesCount -= 1
            ToolStripStatusLabel1.Text = GamesCount & " Games Found"
        Next

        If SavesListView.Items.Count = 0 Then
            BackupsCheckBox.Enabled = False
            UnflagButton.Enabled = False
            ResignCheckBox.Enabled = False
            RestoreBackupsToolStripMenuItem.Enabled = False
            UploadButton.Enabled = False
        End If
        ' Next
    End Sub

    Private Sub ExitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        ftp.Disconnect()
        Me.Close()
    End Sub

    Private Sub RestoreBackupsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RestoreBackupsToolStripMenuItem.Click
        If MessageBox.Show("WARNING: will revert files to there backup file, are you sure?", "Are You sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) Then
            Dim itemscount As Integer = 0
            Do Until itemscount = SavesListView.Items.Count
                If File.Exists(SavesListView.Items(itemscount).SubItems(2).Text & ".bak") Then
                    My.Computer.FileSystem.CopyFile(SavesListView.Items(itemscount).SubItems(2).Text & ".bak", SavesListView.Items(itemscount).SubItems(2).Text, True)
                    LogListBox.Items.Add("   Restored Backup " & SavesListView.Items(itemscount).SubItems(2).Text & ".bak")
                    LogListBox.SelectedIndex = LogListBox.Items.Count - 1
                    LogListBox.SelectedIndex = -1
                    itemscount += 1
                Else
                    itemscount += 1
                End If
            Loop
        End If
        RefreshList()
    End Sub


    Private Sub Settings1ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Settings1ToolStripMenuItem.Click, SetIDsToolStripMenuItem1.Click
        SettingsDialog.ShowDialog()
    End Sub

    Sub Restart(ByVal program As String)
        For Each proc As Process In Process.GetProcesses
            If proc.ProcessName = program Then proc.Kill()
        Next
        Process.Start(program)
    End Sub

    Private Sub DonatePictureBox_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DonatePictureBox.Click
        Process.Start("https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=VR9QCC2FUXDDU&lc=AU&item_name=ConSigner&currency_code=AUD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted")
    End Sub

    Private Sub ShowDonateButtonToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ShowDonateButtonToolStripMenuItem.Click
        DonatePictureBox.Visible = ShowDonateButtonToolStripMenuItem.Checked
    End Sub

    Private Sub ResignCheckBox_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ResignCheckBox.CheckedChanged
        If ResignCheckBox.Checked = True Then
            UnflagButton.Text = "UnCorrupt"
        Else
            UnflagButton.Text = "UnFlag"
        End If
    End Sub

    Private Sub SelectAllToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SelectAllToolStripMenuItem.Click, SelectAllToolStripMenuItem1.Click
        Dim i As Integer = 0
        SavesListView.Focus()
        If SavesListView.SelectedItems.Count = SavesListView.Items.Count Then
            Do Until i = SavesListView.Items.Count
                SavesListView.Items(i).Selected = False
                i += 1
            Loop
        Else
            Do Until i = SavesListView.Items.Count
                SavesListView.Items(i).Selected = True
                i += 1
            Loop
        End If

        Do Until i = SavesListView.Items.Count
            SavesListView.Items(i).Selected = True
            i += 1
        Loop

    End Sub

    Private Sub InvertSelectionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InvertSelectionToolStripMenuItem.Click, InvertSelectedToolStripMenuItem.Click
        Dim i As Integer = 0
        SavesListView.Focus()
        Do Until i = SavesListView.Items.Count
            If SavesListView.Items(i).Selected = True Then
                SavesListView.Items(i).Selected = False
            Else
                SavesListView.Items(i).Selected = True
            End If
            i += 1
        Loop
    End Sub

    Private Sub DownloadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DownloadButton.Click
        SelectProfile2.ListView1.Items.Clear()
        FTPOpen()
        If SavesListView.Items.Count <> 0 Then
            UploadButton.Enabled = True
        End If
    End Sub

    Private Sub Main_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing

        CleanDir()
    End Sub

    Private Sub UploadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UploadButton.Click
        FTPUpload()
        ftp.Disconnect()
    End Sub

    Public Sub CleanDir()
        If Directory.Exists(Application.StartupPath & "\FTP\") Then
            For Each Dfound In Directory.GetDirectories(Application.StartupPath & "\FTP\")
                My.Computer.FileSystem.DeleteDirectory(Dfound, DeleteDirectoryOption.DeleteAllContents)
            Next
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Test()
    End Sub

    Private Sub AboutToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem1.Click
        AboutBox.ShowDialog()
    End Sub

    Private Sub ChilkatLicenceToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChilkatLicenceToolStripMenuItem.Click
        ChilkatDialog.ShowDialog()
    End Sub

    Private Sub GameSavesContextMenuStrip_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles GameSavesContextMenuStrip.Opening
        If SavesListView.Items.Count = 0 Then
            SetIDsFromSelectedToolStripMenuItem.Enabled = False
            RemoveToolStripMenuItem.Enabled = False
            SelectAllToolStripMenuItem1.Enabled = False
            InvertSelectedToolStripMenuItem.Enabled = False
        Else
            SetIDsFromSelectedToolStripMenuItem.Enabled = True
            RemoveToolStripMenuItem.Enabled = True
            SelectAllToolStripMenuItem1.Enabled = True
            InvertSelectedToolStripMenuItem.Enabled = True
        End If
        If SavesListView.SelectedItems.Count <> 1 Then
            SetIDsFromSelectedToolStripMenuItem.Enabled = False
        Else
            SetIDsFromSelectedToolStripMenuItem.Enabled = True
        End If
    End Sub

    Private Sub SetIDsFromSelectedToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SetIDsFromSelectedToolStripMenuItem.Click
        If SavesListView.SelectedItems.Count = 1 Then
            STFSFilePath = SavesListView.Items(SavesListView.SelectedIndices.Item(0)).SubItems(2).Text
            CheckifCON()
            If CheckifCON() = True Then
                ReadIDs()
            End If
            MessageBox.Show("Success", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

    Private Sub SavesListView_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SavesListView.SelectedIndexChanged
        Dim gamertag As String
        Dim GamerPic, TitlePic As Image
        If SavesListView.SelectedIndices.Count <> 0 Then
            Dim index As Integer = SavesListView.SelectedIndices.Item(0).ToString
            Profilepathstring = SavesListView.Items(index).SubItems(2).Text.ToString
            Dim xPackage As New X360.STFS.STFSPackage(Profilepathstring.ToString, Nothing)
            Dim a As X360.STFS.ProfilePackage = New X360.STFS.ProfilePackage(xPackage)

            GamerPic = a.Header.PackageImage
            TitlePic = a.Header.ContentImage
            If a.Header.ThisType = STFS.PackageType.Profile Then
                gamertag = a.UserFile.GetGamertag()
                GamerTagLabel.Text = gamertag
            Else
                '  GamerTagLabel.Text = gamertag
                GamerTagLabel.Text = ""
            End If
            a.CloseIO()
        Else
            GamerPic = Nothing
            TitlePic = Nothing
            GamerTagLabel.Text = ""
            'xPackage.CloseIO()
        End If
            PictureBox1.Image = GamerPic
            PictureBox2.Image = TitlePic
    End Sub

    Private Sub SaveImageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveImageToolStripMenuItem.Click
        Dim image As Image
        image = PictureBox1.Image
        SaveFileDialog1.FileName = "Package Image.png"
        Try
            If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                image.Save(SaveFileDialog1.FileName)
                MessageBox.Show("Extracted image successfully to " & SaveFileDialog1.FileName, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            MessageBox.Show("Please enter a valid filename", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    'Private Sub InjectImageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InjectImageToolStripMenuItem.Click
    '    Dim InjectImage As Image
    '    InjectImage = Image.FromFile(Application.StartupPath & "\test.png")

    '    If SavesListView.SelectedIndices.Count <> 0 Then
    '        Dim index As Integer = SavesListView.SelectedIndices.Item(0).ToString
    '        Profilepathstring = SavesListView.Items(index).SubItems(2).Text.ToString
    '        Dim xPackage As New X360.STFS.STFSPackage(Profilepathstring.ToString, Nothing)
    '        Dim a As X360.STFS.ProfilePackage = New X360.STFS.ProfilePackage(xPackage)
    '        a.ExtractPayload(Application.StartupPath & "\test\", False, True)
    '        InjectImage.Save(Application.StartupPath & "\test\Package Image.png")
    '        Dim x As New X360.Profile.(Application.StartupPath & "\test\")

    '        'a.Header.PackageImage.FromFile(Application.StartupPath & "\test.png") ' = InjectImage
    '        a.CloseIO()
    '        SavesListView_SelectedIndexChanged(sender, e)
    '    End If
    'End Sub


    Private Sub ExtractImageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExtractImageToolStripMenuItem.Click

        Dim image As Image
        image = PictureBox2.Image
        SaveFileDialog1.FileName = "Content Image.png"
        SaveFileDialog1.Filter = "All Files|*.*|PNG|*.png|JPEG|*.jpg|GIF|*.gif"
        Try
            If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                image.Save(SaveFileDialog1.FileName)
                MessageBox.Show("Extracted iamge successfully to " & SaveFileDialog1.FileName, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Catch ex As Exception
            MessageBox.Show("Please enter a valid filename", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Sub

    Private Sub ExtractPackageToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExtractPackageToolStripMenuItem.Click
        FolderBrowserDialog1.SelectedPath = ""
        Dim extractcounter As Integer
        If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

            For Each item In SavesListView.SelectedIndices
                Profilepathstring = SavesListView.Items(item).SubItems(2).Text.ToString
                Dim savenamepath As String = SavesListView.Items(item).SubItems(3).Text
                Dim gamenamepath As String = SavesListView.Items(item).SubItems(0).Text
                Dim xPackage As New X360.STFS.STFSPackage(Profilepathstring.ToString, Nothing)
                Dim a As X360.STFS.ProfilePackage = New X360.STFS.ProfilePackage(xPackage)
                Dim packagefolder As String
                packagefolder = FolderBrowserDialog1.SelectedPath ' & "\" & temp & "\" & """"
                Dim packagename As String
                packagename = packagefolder & "\" & gamenamepath.Replace(":", "-") & "\" & savenamepath.Replace(":", "-").Replace("/", "-").Replace("\", "-") ' & "\"""
                My.Computer.FileSystem.CreateDirectory(packagename)
                a.ExtractPayload(packagename, True, True)
                a.CloseIO()
                'xPackage.CloseIO()
                LogListBox.Items.Add("   Extracted " & savenamepath & " to " & packagename)
                LogListBox.SelectedIndex = LogListBox.Items.Count - 1
                LogListBox.SelectedIndex = -1
            Next
            LogListBox.Items.Add("   " & extractcounter & " packages extracted")
            LogListBox.SelectedIndex = LogListBox.Items.Count - 1
            LogListBox.SelectedIndex = -1
        End If
    End Sub

    Private Sub SetSelectedProfilesToOfflineToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SetSelectedProfilesToOfflineToolStripMenuItem.Click
        Dim BackupPath As String
        Dim BackupCount As Integer
        If MessageBox.Show("Are you sure you want to set the selected Profiles to 'Live Disabled'? Backups will be created in the '/Backups/' folder but if you remove the backups, there is no way to transfer them back to Live enabled, requiring you to recover the profile via Xbox Live.", "!WARNING!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk) = Windows.Forms.DialogResult.Yes Then
            For Each item In SavesListView.SelectedIndices
                Profilepathstring = SavesListView.Items(item).SubItems(2).Text.ToString
                Dim xPackage As New X360.STFS.STFSPackage(Profilepathstring.ToString, Nothing)
                Dim a As X360.STFS.ProfilePackage = New X360.STFS.ProfilePackage(xPackage)

                If a.Header.ThisType = STFS.PackageType.Profile Then
                    If a.UserFile.IsLiveEnabled = True Then
                        If SavesListView.Items(item).SubItems(2).Text.Contains(Application.StartupPath & "\FTP\") Then
                            BackupPath = Application.StartupPath & "\Backups\" & "Original Live Enabled Profiles\" & SavesListView.Items(item).SubItems(2).Text.Replace(Application.StartupPath & "\FTP", "")
                        Else
                            BackupPath = Application.StartupPath & "\Backups\" & "Original Live Enabled Profiles\" & SavesListView.Items(item).SubItems(2).Text.Replace(GetFiles.FolderPath & "\", "")
                        End If
                        a.CloseIO()
                        ' MsgBox(backuppath)
                        If Directory.Exists(BackupPath) = False Then
                            My.Computer.FileSystem.CopyFile(SavesListView.Items(item).SubItems(2).Text, BackupPath, True)
                        End If
                        LogListBox.Items.Add("   Created backup in " & BackupPath)
                        LogListBox.SelectedIndex = LogListBox.Items.Count - 1
                        LogListBox.SelectedIndex = -1
                        BackupCount += 1

                        If File.Exists(BackupPath) Then

                            'File.Delete(SavesListView.Items(item).SubItems(2).Text)
                            'SavesListView.Items.RemoveAt(item)

                            CreateOfflineProfile(Profilepathstring) 'BackupPath) 'Profilepathstring)
                            'If CreateOfflineProfile(Profilepathstring) = True Then
                            a.CloseIO()
                            Dim aPackage As New X360.STFS.STFSPackage(Profilepathstring.ToString, Nothing)
                            Dim b As X360.STFS.ProfilePackage = New X360.STFS.ProfilePackage(aPackage)
                            If b.UserFile.IsLiveEnabled <> True Then
                                LogListBox.Items.Add("   " & Profilepathstring & " is now set to an offline profile")
                                LogListBox.SelectedIndex = LogListBox.Items.Count - 1
                                LogListBox.SelectedIndex = -1
                                a.CloseIO()
                                'FolderPath = Profilepathstring.ToString.Remove(Profilepathstring.ToString.Length - 17, 17)
                                'GetSaves()
                            Else
                                LogListBox.Items.Add("   An error occured in " & Profilepathstring & ", now reverting to the backup")
                                LogListBox.SelectedIndex = LogListBox.Items.Count - 1
                                LogListBox.SelectedIndex = -1
                                a.CloseIO()
                                ' My.Computer.FileSystem.CopyFile(BackupPath, SavesListView.Items(item).SubItems(2).Text, True)
                            End If
                            'Else

                            '    LogListBox.Items.Add("   An error occured in " & Profilepathstring & ", now reverting to the backup")
                            '    LogListBox.SelectedIndex = LogListBox.Items.Count - 1
                            '    LogListBox.SelectedIndex = -1

                            '    My.Computer.FileSystem.CopyFile(BackupPath, SavesListView.Items(item).SubItems(2).Text, True)
                            'End If
                        End If


                    End If
                End If


                a.CloseIO()
            Next
        End If
    End Sub

    Private Sub SetSelectedProfilesToOnlineToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SetSelectedProfilesToOnlineToolStripMenuItem.Click
        For Each item In SavesListView.SelectedIndices
            Profilepathstring = SavesListView.Items(item).SubItems(2).Text.ToString
            Dim xPackage As New X360.STFS.STFSPackage(Profilepathstring.ToString, Nothing)
            Dim a As X360.STFS.ProfilePackage = New X360.STFS.ProfilePackage(xPackage)

            If a.Header.ThisType = STFS.PackageType.Profile Then
                'a.UserFile.SaveMembership(Profile.Membership.Silver)
                MsgBox(a.UserFile.IsLiveEnabled)

                'make a backup

            End If
            a.CloseIO()
        Next
    End Sub

    Private Function CreateOfflineProfile(ByVal FilePath As String) As Boolean

        Dim xPackage As New X360.STFS.STFSPackage(FilePath.ToString, Nothing)
        Dim a As X360.STFS.ProfilePackage = New X360.STFS.ProfilePackage(xPackage)
        a.UserFile.SaveMembership(Profile.Membership.None)
        success = a.UserFile.ForceIntoHDDAccount()
        If success = True Then
            success = a.SaveAccount()
            a.CloseIO()
        Else
            success = False
            a.CloseIO()
        End If
        Return False

        'success = a.MakeHDDAccountCopy(FilePath) 'FilePath) '.ToString.Remove(FilePath.Length - 17, 17) & ".bak") '.ToString.Remove(FilePath.Length - 17, 17)
        a.CloseIO()
    End Function

    Private Sub GamerpicContextMenuStrip_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles GamerpicContextMenuStrip.Opening
        If PictureBox2.Image Is Nothing Then
            SaveImageToolStripMenuItem.Enabled = False
        Else
            SaveImageToolStripMenuItem.Enabled = True
        End If
    End Sub

    Private Sub ContentImageContextMenuStrip_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ContentImageContextMenuStrip.Opening
        If PictureBox1.Image Is Nothing Then
            ExtractImageToolStripMenuItem.Enabled = False
        Else
            ExtractImageToolStripMenuItem.Enabled = True
        End If
    End Sub
End Class
